package org.ThreadDemo.sync;

public class ThreadDeadLock {
    public static void main(String[] args) {
        Object jiangyou = new Object();
        Object cu = new Object();
        //xiaoMIng为其中一个线程
        Thread xiaoMing = new Thread(new Runnable() {
            @Override
            public void run() {
                //让线程小明先获取到"酱油"
                synchronized (jiangyou) {
                    //次数加"sleep"是为了让当前线程获取到对应的锁之后先阻塞
                    //让另外的线程先获取到下面的锁
                    //如果不加sleep，那么有可能其中一个线程同时锁住了两个对象
                    System.out.println("线程1获取到了酱油");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //此时，线程小明会等待小红先释放醋，小明进入阻塞状态
                    synchronized (cu) {
                        System.out.println("小明同时获取到了酱油的醋");
                    }
                }
            }
        });
        xiaoMing.start();


        //xiaoHong为另外一个线程
        Thread xiaoHong = new Thread(new Runnable() {
            @Override
            public void run() {
                //让线程小红先获取到"醋"
                synchronized (cu) {
                    System.out.println("线程2获取到了醋");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //此时，线程小红会等待小明先释放酱油，小红进入阻塞状态
                    synchronized (jiangyou) {
                        System.out.println("小红同时获取到了醋和酱油");
                    }
                }
            }
        });
        xiaoHong.start();
    }

}